package cn.jetpiece.cloud.system.dp.app.modular.envdata.controller;

import cn.hutool.http.HttpRequest;
import cn.hutool.http.HttpResponse;
import cn.hutool.json.JSONUtil;
import cn.jetpiece.cloud.core.util.HttpContext;
import cn.jetpiece.cloud.model.response.Result;
import cn.jetpiece.cloud.system.dp.api.biz.SyncDataApi;
import cn.jetpiece.cloud.system.dp.api.biz.model.params.OpenApiParam;
import cn.jetpiece.cloud.system.dp.app.consts.CommonConstant;
import cn.jetpiece.cloud.system.dp.app.core.aop.annotion.Permission;
import cn.jetpiece.cloud.system.dp.app.modular.biz.entity.DpTApi;
import cn.jetpiece.cloud.system.dp.app.modular.biz.entity.DpTApp;
import cn.jetpiece.cloud.system.dp.app.modular.biz.entity.DpTSystem;
import cn.jetpiece.cloud.system.dp.app.modular.biz.service.IDpTApiService;
import cn.jetpiece.cloud.system.dp.app.modular.biz.service.IDpTAppService;
import cn.jetpiece.cloud.system.dp.app.modular.biz.service.IDpTSystemService;
import cn.jetpiece.cloud.system.dp.app.utils.ErrorStackUtil;
import cn.jetpiece.cloud.system.dp.app.utils.HttpReqUtils;
import cn.jetpiece.cloud.system.dp.app.utils.JwtUtil;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.RestController;
import javax.servlet.http.HttpServletRequest;
import javax.validation.Valid;

@Slf4j
@RestController
public class SynchApiController implements SyncDataApi {

    @Autowired
    private IDpTSystemService dpTSystemService;

    @Autowired
    private IDpTApiService dpTApiService;

    @Autowired
    private IDpTAppService dpTAppService;

    @Override
    @Permission
    public Result<String> getEnvData(@Valid OpenApiParam apiParam) {
        return dispatch(apiParam);
    }

    @Override
    @Permission
    public Result<String> getEnvOrgData(OpenApiParam apiParam) {
        return dispatch(apiParam);
    }

    private Result<String> dispatch(OpenApiParam apiParam) {
        HttpServletRequest request = HttpContext.getRequest();
        try {
            String token = request.getHeader(CommonConstant.AUTHORIZATION);
            String appKey = JwtUtil.getUsername(token);
            DpTApi api = dpTApiService.getByPath(appKey, HttpReqUtils.subServletPath());
            DpTApp app = dpTAppService.getByAppKey(appKey);
            DpTSystem system = dpTSystemService.getById(api.getSystemId());
            HttpResponse response = HttpRequest.post(getUrl(system))
                    .header(CommonConstant.AUTHORIZATION, token)
                    .header(CommonConstant.APPKEY, appKey)
                    .header(CommonConstant.APPSECRET, app.getAppSecret())
                    .body(JSONUtil.toJsonStr(apiParam)).execute();
            if (response.isOk()) {
                return Result.OK(response.body());
            }
            return Result.error(response.body());
        } catch (Exception e) {
            log.error("{}消息转发异常：{}", request.getServletPath(), ErrorStackUtil.getStackTrace(e.getCause()));
            return Result.error(e.getMessage());
        }
    }

    private String getUrl(DpTSystem system) {
        String separator = "/";
        if (system.getSystemUrl().endsWith(separator)) {
            if (HttpReqUtils.subServletPath().startsWith(separator)) {
                return system.getSystemUrl().substring(0, system.getSystemUrl().length() - 1) + HttpReqUtils.subServletPath();
            }
        } else {
            if (!HttpReqUtils.subServletPath().startsWith(separator)) {
                return system.getSystemUrl() + separator + HttpReqUtils.subServletPath();
            }
        }
        return system.getSystemUrl() + HttpReqUtils.subServletPath();
    }

}
